package com.molichuxing.gateway.api.services.impl;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.gateway.api.services.DealerApiService;
import com.molichuxing.gateway.bff.dealer.entity.request.modify.create.StoreCreateVo;
import com.molichuxing.gateway.bff.dealer.entity.request.modify.modify.StoreModifyVerifyStatusVo;
import com.molichuxing.gateway.bff.dealer.entity.response.StoreInfoVo;
import com.molichuxing.gateway.bff.dealer.entity.response.StoreModifyStatusVo;
import com.molichuxing.gateway.bff.dealer.entity.response.StoreModifyVo;
import com.molichuxing.gateway.bff.dealer.entity.response.StoreVo;
import com.molichuxing.gateway.bff.dealer.services.DealerBffService;
import com.molichuxing.gateway.bff.dealer.services.StoreBffService;
import com.molichuxing.gateway.property.StoreStatusAndVerifyEnum;
import com.molichuxing.gateway.utils.RequestAttrUtil;
import com.molichuxing.services.property.StoreStatusEnum;
import com.molichuxing.services.property.StoreVerifyStatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;

/**
 * 经销商相关接口
 *
 * @author zhaopenghui
 * @date 2019年8月26日
 */
@Api(tags = "经销商相关接口")
@RestController
@RequestMapping(value = "/dealer")
public class DealerApiServiceImpl extends RootApiService implements DealerApiService {
    private static final Logger logger = LoggerFactory.getLogger(DealerApiServiceImpl.class);

    @Resource
    DealerBffService dealerBffService;

    @Resource
    StoreBffService storeBffService;


    @Override
    @ApiOperation(value = "查询门店信息")
    @GetMapping(value = "/store")
    public ResponseResult<List<StoreVo>> getStoreByDealerId() {
        ResponseResult<List<StoreVo>> result = new ResponseResult<>();
        Integer dealerId = null;
        try {
            dealerId = RequestAttrUtil.getCurrentDealerId();
            result.success(storeBffService.getStoreByDealerId(dealerId));
        } catch (BizException e) {
            logger.error("[getStoreByDealerId]根据经销商id(" + dealerId + ")查询门店信息异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getStoreByDealerId]根据经销商id(" + dealerId + ")查询门店信息异常", e);
            result.error("查询门店信息异常");
        }
        return result;
    }

    @Override
    @ApiOperation(value = "查询营业中门店信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "notShowStoreId", value = "不显示门店id", required = false, dataType = "Integer"),
    })
    @GetMapping(value = "/open/store")
    public ResponseResult<List<StoreVo>> getOpenStoreByDealerId(Integer notShowStoreId) {
        ResponseResult<List<StoreVo>> result = new ResponseResult<>();
        Integer dealerId = null;
        try {
            dealerId = RequestAttrUtil.getCurrentDealerId();
            result.success(storeBffService.getOpenStoreByDealerId(dealerId, notShowStoreId));
        } catch (BizException e) {
            logger.error("[getOpenStoreByDealerId]根据经销商id(" + dealerId + ")查询门店信息异常:", e);
            result.error(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getOpenStoreByDealerId]根据经销商id(" + dealerId + ")查询门店信息异常", e);
            result.error("查询门店信息异常");
        }
        return result;
    }

    /**
     * 获取门店列表信息
     *
     * @param params
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @ApiOperation(value = "获取门店列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dealerId", value = "经销商id", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "type", value = "状态（0:全部，1：待审核，2：驳回审核，3：营业中，4:暂停营业）", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "sortName", value = "排序字段", required = false, dataType = "String"),
            @ApiImplicitParam(name = "sortWay", value = "排序方式 asc:正序，desc:倒叙", required = false, dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")
    })
    @GetMapping(value = "/dealer/store/list")
    public ResponseResult<Paged<StoreVo>> getStorePage(@RequestParam Map<String, Object> params, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        ResponseResult<Paged<StoreVo>> result = new ResponseResult<>();
        try {
            Object startApplyTime = params.get("startApplyTime");
            Object endApplyTime = params.get("endApplyTime");
            if (startApplyTime != null) {
                LocalDateTime dayStart = ObjectCastUtil.getDayStart(startApplyTime);
                params.put("startApplyTime", dayStart);
            }
            if (endApplyTime != null) {
                LocalDateTime dayEnd = ObjectCastUtil.getDayEnd(endApplyTime);
                params.put("endApplyTime", dayEnd);
            }

            if (null == pageNum) {
                pageNum = 1;
            }
            if (null == pageSize) {
                pageSize = 10;
            }

            Integer type = ObjectCastUtil.castInteger(params.get("type"));
            if (type != null && StoreStatusAndVerifyEnum.ALL.getValue() == type) {
                params.put("type", null);
            } else if (type != null && StoreStatusAndVerifyEnum.UN_VERIFY.getValue() == type) {
                params.put("verifyStatus", StoreVerifyStatusEnum.UN_VERIFY.getValue());
            } else if (type != null && StoreStatusAndVerifyEnum.VERIFY_REJECT.getValue() == type) {
                params.put("verifyStatus", StoreVerifyStatusEnum.VERIFY_REJECT.getValue());
            } else if (type != null && StoreStatusAndVerifyEnum.OPEN.getValue() == type) {
                params.put("status", StoreStatusEnum.OPEN.getValue());
                params.put("verifyStatus", StoreVerifyStatusEnum.VERIFY_PASS.getValue());
            } else if (type != null && StoreStatusAndVerifyEnum.SUSPENSION.getValue() == type) {
                params.put("status", StoreStatusEnum.SUSPENSION.getValue());
                params.put("verifyStatus", StoreVerifyStatusEnum.VERIFY_PASS.getValue());
            } else {
                params.put("verifyStatus", type);
            }

            return result.success(storeBffService.getStorePage(params, pageNum, pageSize));
        } catch (IllegalArgumentException e) {
            logger.error("[getStorePage]获取门店列表信息异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[getStorePage]获取门店列表信息异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getStorePage]获取门店列表信息异常", e);
            result.error("获取门店列表信息异常");
        }
        return result;
    }

    /**
     * 编辑门店信息
     *
     * @param storeModifyVo
     * @return
     */
    @Override
    @ApiOperation(value = "编辑门店信息")
    @PostMapping(value = "/dealer/store/modify")
    public ResponseResult<Boolean> modifyStore(@RequestBody StoreModifyVo storeModifyVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            String businessStartTime = storeModifyVo.getBusinessStartTime();
            String busineesEndTime = storeModifyVo.getBusineesEndTime();
            if (StringUtils.isNoneBlank(businessStartTime) && StringUtils.isNotBlank(busineesEndTime)) {
                LocalTime startTime = DateUtil.parseTime(businessStartTime);
                LocalTime endTime = DateUtil.parseTime(busineesEndTime);
                boolean afterBoolean = endTime.isAfter(startTime);
                if (!afterBoolean) {
                    return result.error("营业时间不正确");
                }
            }

            return result.success(storeBffService.modifyStore(storeModifyVo));
        } catch (IllegalArgumentException e) {
            logger.error("[modifyStore]编辑门店信息异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[modifyStore]编辑门店信息异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[modifyStore]编辑门店信息异常 ", e);
            result.error("编辑门店信息异常");
        }
        return result;
    }

    /**
     * 编辑门店状态
     *
     * @param storeModifyStatusVo
     * @return
     */
    @Override
    @ApiOperation(value = "编辑门店营业状态")
    @PostMapping(value = "/dealer/store/modifyStatus")
    public ResponseResult<Boolean> modifyStoreStatus(@RequestBody StoreModifyStatusVo storeModifyStatusVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            return result.success(storeBffService.modifyStoreStatus(storeModifyStatusVo));
        } catch (IllegalArgumentException e) {
            logger.error("[modifyStoreStatus]编辑门店营业状态异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[modifyStoreStatus]编辑门店营业状态异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[modifyStoreStatus]编辑门店营业状态异常 ", e);
            result.error("编辑门店营业状态异常");
        }
        return result;
    }


    /**
     * 添加门店信息
     *
     * @param storeCreateVo
     * @return
     */
    @Override
    @ApiOperation(value = "添加门店信息")
    @PostMapping(value = "/dealer/store/create")
    public ResponseResult<Boolean> createStore(@RequestBody @Valid StoreCreateVo storeCreateVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            String businessStartTime = storeCreateVo.getBusinessStartTime();
            String busineesEndTime = storeCreateVo.getBusineesEndTime();
            if (StringUtils.isNoneBlank(businessStartTime) && StringUtils.isNotBlank(busineesEndTime)) {
                LocalTime startTime = DateUtil.parseTime(businessStartTime);
                LocalTime endTime = DateUtil.parseTime(busineesEndTime);
                boolean afterBoolean = endTime.isAfter(startTime);
                if (!afterBoolean) {
                    return result.error("营业时间不正确");
                }
            }
            storeCreateVo.setDealerId(RequestAttrUtil.getCurrentDealerId());
            return result.success(storeBffService.createStore(storeCreateVo));
        } catch (IllegalArgumentException e) {
            logger.error("[createStore]添加门店信息异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[createStore]添加门店信息异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[createStore]添加门店信息异常 ", e);
            result.error("添加门店信息异常");
        }
        return result;
    }

    /**
     * 门店审核
     *
     * @param storeModifyVerifyStatusVo
     * @return
     */
    @Override
    @ApiOperation(value = "门店审核")
    @PostMapping(value = "/dealer/store/check/create")
    public ResponseResult<Boolean> modifyStoreVerifyStatus(@RequestBody StoreModifyVerifyStatusVo storeModifyVerifyStatusVo) {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            Integer storeId = storeModifyVerifyStatusVo.getStoreId();
            Integer verifyStatus = storeModifyVerifyStatusVo.getVerifyStatus();
            String rejectReason = storeModifyVerifyStatusVo.getRejectReason();
            String remark = storeModifyVerifyStatusVo.getRemark();

            return result.success(storeBffService.modifyStoreVerifyStatus(storeId, verifyStatus, rejectReason, remark));
        } catch (IllegalArgumentException e) {
            logger.error("[modifyStoreVerifyStatus]门店审核异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[modifyStoreVerifyStatus]门店审核异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[modifyStoreVerifyStatus]门店审核异常 ", e);
            result.error("门店审核异常");
        }
        return result;
    }

    /**
     * 门店详情
     *
     * @param storeId
     * @return
     */
    @Override
    @ApiOperation(value = "门店详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "门店id", required = true, dataType = "Integer"),
    })
    @GetMapping(value = "/dealer/store/datail")
    public ResponseResult<StoreInfoVo> getStoreInfo(@RequestParam Integer storeId) {
        ResponseResult<StoreInfoVo> result = new ResponseResult<>();
        try {
            return result.success(storeBffService.getStoreInfo(storeId));
        } catch (IllegalArgumentException e) {
            logger.error("[getStoreInfo]获取门店详情异常", e);
            result.error(e.getMessage());
        } catch (BizException e) {
            logger.error("[getStoreInfo]获取门店详情异常", e);
            result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("[getStoreInfo]获取门店详情异常", e);
            result.error("获取门店详情异常");
        }
        return result;
    }

}
